'use strict';

const _ = require('lodash');

const Service = require('egg').Service;

class CustomizeSvc extends Service {

  async list(user_id) {
    let result = await this.ctx.model.Customize.find({user_id}).sort({createdAt: -1})
    return result;
  }

  async add(customize) {
    let result = await this.ctx.model.Customize.create(customize);
    return result;
  }

  async edit(customize) {
    let result;
    let now = new Date();
    let record = await this.ctx.model.Customize.findById({_id: customize.id});
    if (customize.type == 'extract') {
      result = this.ctx.model.Customize.findByIdAndUpdate(customize.id, {
        $set: {
          updatedAt: now,
          type: customize.type,
          extract_url: customize.extract_url,
          extract_board: customize.extract_board
        },
        $unset: {weixin_name: '', weixin_code: '', rss_url: ''}
      });
    } else if (customize.type == 'weixin') {
      result = this.ctx.model.Customize.findByIdAndUpdate(customize.id, {
        $set: {
          updatedAt: now,
          type: customize.type,
          weixin_name: customize.weixin_name,
          weixin_code: customize.weixin_code
        },
        $unset: {extract_url: '', extract_board: '', rss_url: ''}
      });
    } else if (customize.type == 'rss') {
      result = this.ctx.model.Customize.findByIdAndUpdate(customize.id, {
        $set: {updatedAt: now, type: customize.type, rss_url: customize.rss_url},
        $unset: {extract_url: '', extract_board: '', weixin_name: '', weixin_code: ''}
      });
    }
    return result;
  }


  async delete(id, user_id) {
    let result = await this.ctx.model.Customize.remove({_id: id, user_id});
    return result.result.n;
  }
}


module.exports = CustomizeSvc;
